package com.quan.generator.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quan.commons.core.core.MyBaseServiceImpl;
import com.quan.commons.core.utils.PageUtils;
import com.quan.generator.entity.TableEntity;
import com.quan.generator.mapper.MySQLGeneratorMapper;
import com.quan.generator.service.MySQLGeneratorService;
import com.quan.generator.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service
public class MySQLGeneratorServiceImpl extends MyBaseServiceImpl<MySQLGeneratorMapper, TableEntity> implements MySQLGeneratorService {

    @Autowired
    private MySQLGeneratorMapper mapper;

    public IPage<Map<String, Object>> selectTables(PageUtils pageUtils, Map<String, Object> params) {
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageUtils.getPage(), pageUtils.getLimit());

        // 排序
        if (StringUtils.isNotBlank(pageUtils.getSortColumns())) {
            // 排序字段“,”逗号分割
            String[] sortColumns = pageUtils.getSortColumns().split(",");

            if (pageUtils.getSortType().equalsIgnoreCase("DESC")) {
                page.setOrders(OrderItem.descs(sortColumns));
            } else {
                page.setOrders(OrderItem.ascs(sortColumns));
            }
        }

        return this.mapper.selectTables(page, params);
    }


    public List<Map<String, String>> selectDatabase(Map<String, Object> params) {
        return mapper.selectDatabase(params);
    }

    public Map<String, String> selectTable(Map<String, Object> params) {
        return mapper.selectTable(params);
    }

    public List<Map<String, String>> selectColumns(Map<String, Object> params) {
        return mapper.selectColumns(params);
    }


    public byte[] generatorCode(String database, String packageName, String moduleName, String[] tables) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("database", database);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tables) {
            params.put("tableName", tableName);
            //查询表信息
            Map<String, String> table = selectTable(params);
            //查询列信息
            List<Map<String, String>> columns = selectColumns(params);
            //生成代码
            GenUtils.generatorCode(packageName, moduleName, table, columns, zip);
        }

        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
